package light.mvc.utils;  
  
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TimeZone;

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
  
/** 
 * 文件上传工具类 
 *  
 * @author Chris Mao(Zibing) 
 * 
 */  
public class FileUploadingUtil {  
  
	
    /** 
     * 服务器上的保存路径，在使用到上传功能的Controller中对其进行赋值 
     */  
    public static String FILEDIR = null;  
  
    public static Map<String,String> getUploaded(HttpServletRequest request) throws Exception {
		FILEDIR = request.getServletContext().getRealPath("") + GlobalConstant.uploadFolder;
		Map<String,String> uploadedFiles = null;
		
		//根据request上下文构建multipartResolver
		System.out.println(request.getContentType());
		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
				request.getSession().getServletContext());
		//判断请求是否为multipart请求,是的话转化为MultipartHttpServletRequest
		if (multipartResolver.isMultipart(request)) {
			try {  
	            MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest)request;  
	            
	            uploadedFiles = upload(mRequest.getFileMap());  
	  
	            /*Iterator<Entry<String, String>> iter = uploadedFiles.entrySet().iterator();  
	            while (iter.hasNext()) {  
	                Entry<String, String> each = iter.next();  
	                System.out.print("Uploaded File Name = " + each.getKey());  
	                System.out.println(", Saved Path in Server = " + each.getValue());  
	                fileUrl = each.getValue();
	            }*/  
	        } catch (Exception e) {  
	            throw e;  
	        }
		}
		
		return uploadedFiles;
	}
    
    /** 
     * 上传多个文件，返回文件名称和服务器存储路径列表 
     *  
     * @param files 
     * @return 
     * @throws IOException 
     */  
    private static Map<String, String> upload(Map<String, MultipartFile> files) throws IOException {  
        File file = new File(FILEDIR);  
        if (!file.exists()) {  
            file.mkdir();  
        }  
  
        Map<String, String> result = new HashMap<String, String>();  
        Iterator<Entry<String, MultipartFile>> iter = files.entrySet().iterator();  
        while (iter.hasNext()) {
        	Entry<String,MultipartFile> fileMap = iter.next();
        	String keyName = fileMap.getKey();
            MultipartFile aFile = fileMap.getValue();  
            if (aFile.getSize() != 0 && !"".equals(aFile.getName())) {
            	String originalName = aFile.getOriginalFilename();
            	String fileName = UUIDGenerator.getUUID() + originalName.substring(originalName.lastIndexOf('.'));
                result.put(keyName, uploadFile(keyName,fileName,aFile));  
            }  
        }  
        return result;  
    }  
  
    /** 
     * 上传单个文件，并返回其在服务器中的存储路径 
     *  
     * @param aFile 
     * @return 
     * @throws FileNotFoundException 
     * @throws IOException 
     */  
    private static String uploadFile(String keyName,String fileName,MultipartFile aFile) throws IOException {  
//        String filePath = initFilePath(aFile.getOriginalFilename());
		Calendar c = Calendar.getInstance(TimeZone.getTimeZone("GMT+08:00"));    //获取东八区时间

		int year = c.get(Calendar.YEAR);    //获取年
		int month = c.get(Calendar.MONTH) + 1;   //获取月份，0表示1月份
		int day = c.get(Calendar.DAY_OF_MONTH);    //获取当前天数
		String date = year + "-" + month + "-" + day;
		
		String filePath = FILEDIR + File.separator + date + File.separator;
		
		if(keyName.equals("file")) {
			filePath +=  "face" + File.separator ;
		} else if(keyName.equals("tongueFile")) {
			filePath += "tongue" + File.separator;
		} else if(keyName.equals("prescription")) {
			filePath += "prescription" + File.separator;
		}
		
		File dir = new File(filePath);
		if(!dir.exists()) {
			dir.mkdirs();
		}
    
        filePath = filePath + fileName; 
        
        File file = new File(filePath);
        if(!file.exists()) {
        	file.createNewFile();
        }
        
        try {  
            write(aFile.getInputStream(), new FileOutputStream(filePath));  
        } catch (FileNotFoundException e) {
            e.printStackTrace();  
        }  
        return filePath;  
    }  
  
    /** 
     * 写入数据 
     *  
     * @param in 
     * @param out 
     * @throws IOException 
     */  
    private static void write(InputStream in, OutputStream out) throws IOException {  
        try {  
            byte[] buffer = new byte[1024];  
            int bytesRead = -1;  
            while ((bytesRead = in.read(buffer)) != -1) {  
                out.write(buffer, 0, bytesRead);  
            }  
            out.flush();  
        } finally {  
            try {  
                in.close();  
                out.close();  
            } catch (IOException ex) {  
            }  
        }  
    }  
  
    /** 
     * 遍历服务器目录，列举出目录中的所有文件（含子目录） 
     * @return 
     */  
    public static Map<String, String> getFileMap() {  
        Map<String, String> map = new HashMap<String, String>();  
        File[] files = new File(FileUploadingUtil.FILEDIR).listFiles();  
        if (files != null) {  
            for (File file : files) {  
                if (file.isDirectory()) {  
                    File[] files2 = file.listFiles();  
                    if (files2 != null) {  
                        for (File file2 : files2) {  
                            String name = file2.getName();   
                            map.put(file2.getParentFile().getName() + "/" + name,  
                                    name.substring(name.lastIndexOf("_") + 1));  
                        }  
                    }  
                }  
            }  
        }  
        return map;  
    }  
  
    /** 
     * 返回文件存储路径，为防止重名文件被覆盖，在文件名称中增加了随机数 
     * @param name 
     * @return 
     */  
    private static String initFilePath(String name) {  
        String dir = getFileDir(name) + "";  
        File file = new File(FILEDIR + dir);  
        if (!file.exists()) {  
            file.mkdir();  
        }  
        Long num = new Date().getTime();  
        Double d = Math.random() * num;  
        return (file.getPath() + "/" + num + d.longValue() + "_" + name).replaceAll(" ", "-");  
    }  
  
    /** 
     *  
     * @param name 
     * @return 
     */  
    private static int getFileDir(String name) {  
        return name.hashCode() & 0xf;  
    }  
}  